<template>
  <view class="image-upload-component">
    <!-- 上传区域 -->
    <view 
      class="upload-area" 
      @click="chooseImages"
      :class="{ disabled: uploading }"
    >
      <view class="upload-icon">
        <text>+</text>
      </view>
      <text class="upload-text">点击选择图片</text>
      <text class="upload-hint">支持多张图片上传</text>
    </view>
    
    <!-- 图片预览网格 -->
    <view v-if="imageList.length > 0" class="image-preview-grid">
      <view v-for="(image, index) in imageList" :key="index" class="image-item">
        <image 
          :src="image.path" 
          mode="aspectFill" 
          class="preview-image"
        ></image>
        <view class="image-overlay">
          <text class="image-name">{{ image.name }}</text>
          <text class="image-size">{{ formatFileSize(image.size) }}</text>
          <view 
            class="delete-btn"
            @click.stop="removeImage(index)"
            :disabled="uploading"
          >
            <text>✕</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 图片信息输入 -->
    <view v-if="imageList.length > 0" class="input-section">
      <!-- 图片标题输入 -->
      <view class="input-group">
        <text class="input-label">图片标题 <text class="required">*</text></text>
        <input 
          class="input-field"
          v-model="imageTitle"
          placeholder="请输入图片标题（最多50字）"
          maxlength="50"
          :disabled="uploading"
        />
      </view>
      
      <!-- 图片描述输入 -->
      <view class="input-group">
        <text class="input-label">图片描述</text>
        <textarea 
          class="textarea-field"
          v-model="imageDescription"
          placeholder="请输入图片描述（选填，最多500字）"
          maxlength="500"
          rows="4"
          :disabled="uploading"
        />
      </view>
    </view>
    
    <!-- 上传操作按钮 -->
    <view v-if="imageList.length > 0" class="action-buttons">
      <button 
        class="btn-primary"
        @click="uploadImages"
        :disabled="uploading"
      >
        {{ uploading ? '上传中...' : '开始上传' }}
      </button>
      <button 
        class="btn-secondary"
        @click="resetUpload"
        :disabled="uploading"
      >
        清空选择
      </button>
    </view>
    
    <!-- 上传进度 -->
    <view v-if="uploading" class="progress-container">
      <text class="progress-text">上传进度: {{ uploadProgress }}%</text>
      <view class="progress-bar">
        <view 
          class="progress-fill"
          :style="{ width: uploadProgress + '%' }"
        ></view>
      </view>
      <text class="progress-detail">{{ currentUploadIndex + 1 }}/{{ imageList.length }} 张图片</text>
    </view>
    
    <!-- 上传成功提示 -->
    <view v-if="uploadSuccess" class="success-message">
      <text class="success-icon">✓</text>
      <text class="success-text">{{ imageList.length }} 张图片上传成功！</text>
    </view>
    
    <!-- 上传错误提示 -->
    <view v-if="uploadError" class="error-message">
      <text class="error-icon">✗</text>
      <text class="error-text">{{ uploadError }}</text>
    </view>
    
    <!-- 上传规则提示 -->
    <view class="upload-rules">
      <text class="rule-item">• 支持 JPG、PNG、GIF 等常见图片格式</text>
      <text class="rule-item">• 单张图片大小不超过 10MB</text>
      <text class="rule-item">• 最多可同时上传 9 张图片</text>
    </view>
  </view>
</template>

<script>
import { uploadImageFile } from '@/utils/api.js';

export default {
  data() {
    return {
      imageList: [],
      imageTitle: '',
      imageDescription: '',
      uploading: false,
      uploadProgress: 0,
      currentUploadIndex: 0,
      uploadSuccess: false,
      uploadError: ''
    }
  },
  methods: {
    // 选择图片
    chooseImages() {
      if (this.uploading) return;
      
      uni.chooseImage({
        count: 9 - this.imageList.length, // 限制最多9张图片
        mediaType: ['image'],
        sourceType: ['album', 'camera'],
        sizeType: ['original', 'compressed'],
        success: (res) => {
          if (res.tempFiles && res.tempFiles.length > 0) {
            this.handleImageSelect(res.tempFiles);
          }
        },
        fail: (err) => {
          console.error('选择图片失败:', err);
          uni.showToast({
            title: '选择图片失败',
            icon: 'none'
          });
        }
      });
    },
    
    // 处理选择的图片文件
    handleImageSelect(imageFiles) {
      // 重置上传状态
      this.uploadSuccess = false;
      this.uploadError = '';
      
      // 检查图片大小限制（10MB）
      for (const file of imageFiles) {
        if (file.size > 10 * 1024 * 1024) {
          uni.showToast({
            title: '图片大小不能超过10MB',
            icon: 'none'
          });
          return;
        }
      }
      
      // 添加新选择的图片
      const newImages = imageFiles.map(file => ({
        path: file.tempFilePath || file.path,
        size: file.size || 0,
        name: this.getFileName(file.tempFilePath || file.path)
      }));
      
      this.imageList = [...this.imageList, ...newImages];
    },
    
    // 获取文件名
    getFileName(filePath) {
      const parts = filePath.split('/');
      return parts[parts.length - 1];
    },
    
    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes === 0) return '0 Bytes';
      const k = 1024;
      const sizes = ['Bytes', 'KB', 'MB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },
    
    // 移除图片
    removeImage(index) {
      if (this.uploading) return;
      
      // 弹出确认框
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这张图片吗？',
        success: (res) => {
          if (res.confirm) {
            this.imageList.splice(index, 1);
            // 如果删除所有图片，重置相关状态
            if (this.imageList.length === 0) {
              this.imageTitle = '';
              this.imageDescription = '';
              this.uploadSuccess = false;
              this.uploadError = '';
            }
          }
        }
      });
    },
    
    // 上传图片
    async uploadImages() {
      // 检查图片标题是否为空
      if (!this.imageTitle.trim()) {
        uni.showToast({
          title: '请输入图片标题',
          icon: 'none'
        });
        return;
      }
      
      this.uploading = true;
      this.uploadProgress = 0;
      this.currentUploadIndex = 0;
      this.uploadSuccess = false;
      this.uploadError = '';
      
      try {
        // 模拟上传进度
        this.simulateProgress();
        
        // 模拟上传图片（实际项目中应调用真实的上传API）
        await this.simulateImageUpload();
        
        this.uploadProgress = 100;
        this.uploadSuccess = true;
        
        // 显示上传成功提示
        uni.showToast({
          title: '上传成功',
          icon: 'success'
        });
        
        console.log('图片上传成功');
      } catch (error) {
        this.uploadError = error.message || '上传失败，请重试';
        uni.showToast({
          title: this.uploadError,
          icon: 'none'
        });
      } finally {
        this.uploading = false;
      }
    },
    
    // 模拟上传进度
    simulateProgress() {
      let progress = 0;
      const interval = setInterval(() => {
        if (this.uploading) {
          progress += Math.random() * 5;
          if (progress >= 95) {
            progress = 95; // 保留最后5%进度给最终完成
          }
          this.uploadProgress = Math.floor(progress);
        } else {
          clearInterval(interval);
        }
      }, 300);
    },
    
    // 上传图片
    async uploadImages() {
      // 检查图片标题是否为空
      if (!this.imageTitle.trim()) {
        uni.showToast({
          title: '请输入图片标题',
          icon: 'none'
        });
        return;
      }
      
      this.uploading = true;
      this.uploadProgress = 0;
      this.currentUploadIndex = 0;
      this.uploadSuccess = false;
      this.uploadError = '';
      
      try {
        // 实际调用图片上传API
        for (let i = 0; i < this.imageList.length; i++) {
          this.currentUploadIndex = i;
          
          // 调用上传API，并传入进度回调
          await uploadImageFile({
            imagePath: this.imageList[i].path,
            imageTitle: this.imageTitle,
            imageDescription: this.imageDescription,
            // 添加进度回调函数，考虑多图上传的整体进度
            onProgressUpdate: (progress) => {
              // 计算当前图片在整体上传中的进度贡献
              const imageBaseProgress = (i / this.imageList.length) * 100;
              const imageProgressContribution = (progress / 100) * (100 / this.imageList.length);
              this.uploadProgress = Math.floor(imageBaseProgress + imageProgressContribution);
            }
          });
        }
        
        this.uploadProgress = 100;
        this.uploadSuccess = true;
        
        // 显示上传成功提示
        uni.showToast({
          title: '上传成功',
          icon: 'success'
        });
        
        console.log('图片上传成功');
      } catch (error) {
        this.uploadError = error.message || '上传失败，请重试';
        uni.showToast({
          title: this.uploadError,
          icon: 'none'
        });
      } finally {
        this.uploading = false;
      }
    },
    
    // 重置上传
    resetUpload() {
      // 弹出确认框
      uni.showModal({
        title: '确认清空',
        content: '确定要清空所有已选择的图片吗？',
        success: (res) => {
          if (res.confirm) {
            this.imageList = [];
            this.imageTitle = '';
            this.imageDescription = '';
            this.uploading = false;
            this.uploadProgress = 0;
            this.currentUploadIndex = 0;
            this.uploadSuccess = false;
            this.uploadError = '';
          }
        }
      });
    }
  }
}
</script>

<style>
.image-upload-component {
  width: 100%;
}

/* 上传区域 */
.upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 2rpx dashed #dcdfe6;
  border-radius: 16rpx;
  padding: 60rpx 20rpx;
  background-color: #f5f7fa;
  transition: all 0.3s ease;
  cursor: pointer;
}

.upload-area:hover {
  border-color: #667eea;
  background-color: #edf2fc;
}

.upload-area.disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.upload-icon {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  background-color: #667eea;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
}

.upload-icon text {
  font-size: 72rpx;
  line-height: 1;
  font-weight: 300;
}

.upload-text {
  font-size: 32rpx;
  color: #303133;
  margin-bottom: 10rpx;
}

.upload-hint {
  font-size: 24rpx;
  color: #909399;
}

/* 图片预览网格 */
.image-preview-grid {
  margin-top: 40rpx;
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.image-item {
  width: calc(33.333% - 14rpx);
  aspect-ratio: 1;
  position: relative;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.preview-image {
  width: 100%;
  height: 100%;
}

.image-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
  padding: 10rpx;
  color: white;
}

.image-name {
  display: block;
  font-size: 20rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-bottom: 4rpx;
}

.image-size {
  display: block;
  font-size: 18rpx;
  opacity: 0.8;
}

.delete-btn {
  position: absolute;
  top: 10rpx;
  right: 10rpx;
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 32rpx;
  transition: all 0.3s ease;
}

.delete-btn:hover {
  background-color: rgba(245, 108, 108, 0.8);
}

/* 输入区域 */
.input-section {
  margin-top: 40rpx;
}

.input-group {
  margin-top: 30rpx;
}

.input-label {
  display: block;
  font-size: 28rpx;
  color: #606266;
  margin-bottom: 12rpx;
}

.required {
  color: #f56c6c;
}

.input-field {
  width: 100%;
  height: 88rpx;
  background-color: #f5f7fa;
  border: 1rpx solid #dcdfe6;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #303133;
  box-sizing: border-box;
  transition: border-color 0.3s ease;
}

.input-field:focus {
  border-color: #667eea;
  outline: none;
}

.textarea-field {
  width: 100%;
  background-color: #f5f7fa;
  border: 1rpx solid #dcdfe6;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 28rpx;
  color: #303133;
  box-sizing: border-box;
  resize: none;
  transition: border-color 0.3s ease;
}

.textarea-field:focus {
  border-color: #667eea;
  outline: none;
}

/* 操作按钮 */
.action-buttons {
  margin-top: 40rpx;
  display: flex;
  gap: 20rpx;
}

.btn-primary {
  flex: 1;
  height: 96rpx;
  background-color: #667eea;
  color: white;
  border: none;
  border-radius: 12rpx;
  font-size: 32rpx;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.btn-primary:hover {
  background-color: #5a67d8;
  transform: translateY(-2rpx);
  box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
}

.btn-primary:disabled {
  background-color: #c0c4cc;
  transform: none;
  box-shadow: none;
}

.btn-secondary {
  flex: 1;
  height: 96rpx;
  background-color: #f5f7fa;
  color: #606266;
  border: 1rpx solid #dcdfe6;
  border-radius: 12rpx;
  font-size: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.btn-secondary:hover {
  color: #667eea;
  border-color: #667eea;
  background-color: #edf2fc;
}

.btn-secondary:disabled {
  color: #909399;
  border-color: #dcdfe6;
  background-color: #f5f7fa;
}

/* 进度条 */
.progress-container {
  margin-top: 30rpx;
}

.progress-text {
  display: block;
  font-size: 28rpx;
  color: #606266;
  margin-bottom: 12rpx;
}

.progress-bar {
  height: 12rpx;
  background-color: #e0e0e0;
  border-radius: 6rpx;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
  border-radius: 6rpx;
  transition: width 0.3s ease;
}

.progress-detail {
  display: block;
  font-size: 24rpx;
  color: #909399;
  margin-top: 8rpx;
  text-align: right;
}

/* 消息提示 */
.success-message,
.error-message {
  margin-top: 30rpx;
  padding: 20rpx;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
}

.success-message {
  background-color: #f0f9ff;
  border: 1rpx solid #bae7ff;
}

.error-message {
  background-color: #fef0f0;
  border: 1rpx solid #fbc4c4;
}

.success-icon,
.error-icon {
  font-size: 32rpx;
  margin-right: 10rpx;
}

.success-icon {
  color: #67c23a;
}

.error-icon {
  color: #f56c6c;
}

.success-text,
.error-text {
  font-size: 28rpx;
}

.success-text {
  color: #36cfc9;
}

.error-text {
  color: #f56c6c;
}

/* 上传规则 */
.upload-rules {
  margin-top: 30rpx;
  padding: 20rpx;
  background-color: #fafafa;
  border-radius: 8rpx;
}

.rule-item {
  display: block;
  font-size: 24rpx;
  color: #909399;
  margin-bottom: 8rpx;
}

.rule-item:last-child {
  margin-bottom: 0;
}
</style>